package {
	import com.adobe.serialization.json.*;
	import flash.text.TextFormat;
	
	import flash.display.*;
	import flash.events.*;
	import flash.external.ExternalInterface;
	import flash.net.*;
	import flash.system.*;
	import flash.ui.*;
	import flash.utils.*;
	import fl.transitions.Tween;
	import fl.transitions.easing.*;

	public class Twitpic extends MovieClip {
        private var uploadURL:URLRequest;
        private var file:FileReference;
		private var _id:String;
		private var _url:String;
		private var _service:String;
		private var _password:String;
        private var _loginId:String;
		private var _iid:Number ;
		
		public function Twitpic() {
			Security.allowDomain('*');
			var paramObj:Object = LoaderInfo(this.root.loaderInfo).parameters;
			_id = paramObj.id == undefined ? 'egoing' : paramObj.id;
			_url = paramObj.url == undefined ? 'http://dtwitter.egoing.net/' : paramObj.url;
			_loginId = '';
			_service = 'twitpic';
			stage.scaleMode = StageScaleMode.NO_SCALE;
			stage.align = 'lt';
			uploadURL = new URLRequest();
			var tf:TextFormat = new TextFormat(null, 14, 0x444444);
			button.setStyle('textFormat',tf);
			button.buttonMode = true;
			button.useHandCursor  = true;
			button.addEventListener(MouseEvent.CLICK, function(e:MouseEvent) {
				if (ExternalInterface.available) {
					ExternalInterface.addCallback('fileSelect', fileBrowse);
					ExternalInterface.addCallback('run', run);
				}
				run();
			});
			em.addEventListener(MouseEvent.MOUSE_OVER, function(e:MouseEvent) {
				emphasized(false);
			});
			em.visible = false;
			stage.addEventListener(Event.RESIZE, function(e:Event) {
				repaint();
			});
			repaint();
        }
		
		private function repaint() {
			em.height = button.height = stage.stageHeight;
			em.width = button.width = stage.stageWidth;
		}
		
		function run() {
			var o:String = ExternalInterface.call('$.cookie', _id + '_' + _service + '_auth');
			try {
				var _p = JSON.decode(o);
			} catch (e:Error) {
				ExternalInterface.call('login', 'twitpic',Config.TWITPIC_MESSAGE_REQUIRE_AUTH, true);
				return;
			}
			if (_p==undefined || _p.id == undefined || _p.id == null || _p.password == undefined || _p.password == null) {
				ExternalInterface.call('login','twitpic', Config.TWITPIC_MESSAGE_REQUIRE_AUTH , true);
			} else {
				_password = _p.password;
				_loginId = _p.id;
				
				try{
					fileBrowse();
				} catch (e:Error) {
					emphasized();
				}
				
			}

		}
		
		function emphasized(on:Boolean = true) {
			if (!on) {
				clearInterval(_iid);
				em.visible = false;
				return;
			}
			var myTweenAlpha:Tween;
			var i:Number = 0;			
			em.visible = true;
			_iid = setInterval(function() {
				if (i > 8) {
					clearInterval(_iid);
					em.visible = false;
				}
				if (i % 2) {
					myTweenAlpha = new Tween(em, "alpha", Strong.easeOut, 0.3, 0, 0.3, true);
				} else {
					myTweenAlpha = new Tween(em, "alpha", Strong.easeOut, 0, 0.3, 0.3, true);
				}
				i++;
			}, 200);
		}
		
		function fileBrowse() {
			var urlVal = new URLVariables();
			button.label = 'photo';
			urlVal.username = _loginId;
			urlVal.password = _password;
			urlVal.mode = 'upload';
			uploadURL.data = urlVal;
            uploadURL.url = _url+'control.php';
            uploadURL.method = URLRequestMethod.POST
			file = new FileReference();
			configureListeners(file);
			file.browse(getTypes());
		}
        private function configureListeners(dispatcher:IEventDispatcher):void {
            dispatcher.addEventListener(Event.CANCEL, cancelHandler);
            dispatcher.addEventListener(Event.COMPLETE, completeHandler);
            dispatcher.addEventListener(HTTPStatusEvent.HTTP_STATUS, httpStatusHandler);
            dispatcher.addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler);
            dispatcher.addEventListener(Event.OPEN, openHandler);
            dispatcher.addEventListener(ProgressEvent.PROGRESS, progressHandler);
            dispatcher.addEventListener(SecurityErrorEvent.SECURITY_ERROR, securityErrorHandler);
            dispatcher.addEventListener(Event.SELECT, selectHandler);
            dispatcher.addEventListener(DataEvent.UPLOAD_COMPLETE_DATA,uploadCompleteDataHandler);
        }

        private function getTypes():Array {
            var allTypes:Array = new Array(getImageTypeFilter(), getTextTypeFilter());
            return allTypes;
        }

        private function getImageTypeFilter():FileFilter {
            return new FileFilter("Images (*.jpg, *.jpeg, *.gif, *.png)", "*.jpg;*.jpeg;*.gif;*.png");
        }

        private function getTextTypeFilter():FileFilter {
            return new FileFilter("Text Files (*.txt, *.rtf)", "*.txt;*.rtf");
        }

        private function cancelHandler(event:Event):void {
            trace("cancelHandler: " + event);
			button.enabled = true;
        }

        private function completeHandler(event:Event):void {
            trace("completeHandler: " + event);
			button.label = 'photo';
			button.enabled = true;
        }

        private function uploadCompleteDataHandler(event:DataEvent):void {
            trace("uploadCompleteData: " + event);
			try{
				var resultML:XML = new XML(event.data);
				trace('resultML',resultML);
				if (resultML.@stat == 'ok') {
					ExternalInterface.call('insertPhoto', resultML.mediaurl.toString());
				} else {
					var result = (resultML.err.@code).toString();
					switch(result) {
						case '1001':
							ExternalInterface.call('login','twitpic', Config.TWITPIC_MESSAGE_WRONG_PASSWORD, true);
							break;
						case '1002':
							ExternalInterface.call('alert', 'Image not found');
							break;
						case '1003':
							ExternalInterface.call('alert', 'Invalid image type');
							break;
						case '1004':
							ExternalInterface.call('alert', 'Image larger than 4MB ');
							break;
					}
				}
			} catch (e:Error) {
				ExternalInterface.call('alert', 'error');
			}
			button.label = 'photo';
        }

        private function httpStatusHandler(event:HTTPStatusEvent):void {
            trace("httpStatusHandler: " + event);
        }
        
        private function ioErrorHandler(event:IOErrorEvent):void {
            trace("ioErrorHandler: " + event);
        }

        private function openHandler(event:Event):void {
            trace("openHandler: " + event);
			button.label = '+ing';
			button.enabled = false;
        }

        private function progressHandler(event:ProgressEvent):void {
            var file:FileReference = FileReference(event.target);
			button.label = 'Uploading ' + Math.ceil(event.bytesLoaded / event.bytesTotal * 100) + '%';
			if (event.bytesLoaded == event.bytesTotal) {
				button.label = 'Processing...';
			}
        }

        private function securityErrorHandler(event:SecurityErrorEvent):void {
            trace("securityErrorHandler: " + event);
        }

        private function selectHandler(event:Event):void {
            
			var file:FileReference = FileReference(event.target);
            if (file.size > Config.TWITPIC_MESSAGE_FILESIZE_LIMIT) {
				ExternalInterface.call('alert', Config.TWITPIC_MESSAGE_FILESIZE);
				return;
			}
			file.upload(uploadURL, 'media');
        }
		
		

    }
}
